var response,imagesize,jcrop_api, boundx, boundy,
    $preview = $('#preview-pane'),
    $pcnt = $('#preview-pane .preview-container'),
    $pimg = $('#preview-pane .preview-container img'),
    xsize = $pcnt.width(),
    ysize = $pcnt.height();
	
	function updatePreview(c)
    {
      if (parseInt(c.w) > 0)
      {
      	
      	var rx = xsize / c.w;
        var ry = ysize /c.h;
        
        console.log(c.x,c.y,c.x2,c.y2);
        
        
        //console.log("__1__"+Math.round(rx * boundx)+"__2__"+Math.round(ry * boundy)+"__3__"+Math.round(rx * c.x)+"__4__"+Math.round(ry * c.y));
        $pimg.css({
          width: Math.round(rx * boundx) + 'px',
          height: Math.round(ry * boundy) + 'px',
          marginLeft: '-' + Math.round(rx * c.x) + 'px',
          marginTop: '-' + Math.round(ry * c.y) + 'px'
        });
      }
    };
    
function UpladFile() {
    var fiv = document.querySelector("input[type=file]").value;
    if (!!fiv) {

        var obj = jcrop_api.tellSelect();

        var fileObj = document.getElementById("btn_file").files[0];
        var FileController = $.session.get('back_url') + "upload/uploadImage";
        var form = new FormData();
        form.append("x", obj.x);
        form.append("y", obj.y);
        form.append("w", obj.w);
        form.append("h", obj.h);
        form.append("token", $.session.get('token'));
        form.append("file", fileObj);

        form.append("imgtype","sug");
        form.append("appid", $.session.get('appId'));
        var xhr = new XMLHttpRequest();
        xhr.open("post", FileController, true);
        xhr.onload = function(data) {

            response = JSON.parse(data.currentTarget.response);
            if (response.code == "200") {
                //getQiniuImg(response.path);
                if(avalon.vmodels[window.init_page] && avalon.vmodels[window.init_page].getQiniuImg)
				avalon.vmodels[window.init_page].getQiniuImg(response.body);
                // closeOut();
                //alert(1);
            } else {
                alert("图片裁剪失败请更换图片");
            }

        };
        xhr.send(form);
    } else {
        sAlert("请不要使用默认图片");
    }
}

//获取本地图片
function getFullPath(obj) {
    if (obj) { //ie
        if (window.navigator.userAgent.indexOf("MSIE") >= 1) {
            obj.select();
            return document.selection.createRange().text;
        } //firefox
        else if (window.navigator.userAgent.indexOf("Firefox") >= 1) {
            if (obj.files) {
                return window.URL.createObjectURL(obj.files.item(0));
            }
            return obj.value;
        } else if (window.navigator.userAgent.indexOf("Chrome") >= 1) {
            if (obj.files) {
                return window.URL.createObjectURL(obj.files.item(0));
            }
            return obj.value;
        } else { //默认使用obj.files
            if (obj.files) {
                return window.URL.createObjectURL(obj.files.item(0));
            }
            return obj.value;
        }
        return obj.value;
    }
}

var img = new Image();
var obj;

function changeImg(obj) {
    console.log(obj);
    $(".upload").hide();
	$(".imginput").hide();
	$(".tishiwenzi").hide();
	$(".jcrop-tracker").css("pointer-events","all");
    var filepath = $("#btn_file")[0].value;
    filepath = filepath.substring(filepath.lastIndexOf('.') + 1, filepath.length);
    filepath=filepath.toLowerCase();
    if (filepath != 'png'&&filepath != 'jpg') {
		sAlert('仅支持jpg和png格式');
		setTimeout(function () { 
	       	$(".upload").show();
			$(".imginput").show();
			$(".tishiwenzi").show();
	    }, 1500);

		
        return;
    }
    this.obj = obj;
    //构造JS的Image对象
    var img=$('#cropbox');
    img.src = getFullPath(obj);
    if (0 != img.src.indexOf("blob")) {
        jcrop_api.setImage('../images/toupdefault.png');
		
        
        return;
    }
    setTimeout("chgImg(obj)", 1000);
}

function chgImg() {
	var img=$('#cropbox');
    boundx = img.width;
    boundy = img.height;
    $('.jcrop-holder').css({'top': 0, 'display': 'none'});
    $('#preview-pane').css({'display': 'none'});
    if (img.height < parent.minheight || img.width < parent.minwidth) {
        sAlert('图片格式错误,图片尺寸应大于等于' + parent.minwidth + '*' + parent.minheight);
        	setTimeout(function(){
        		$(".jcrop-holder").show();
        		$("#preview-pane").show();
        		$(".upload").show();
				$(".imginput").show();
				$(".tishiwenzi").show();
        	},1500);
        $("#btn_file")[0].value = '';
        return;
    }

    if (img.height < parent.suggestwidth || img.height < parent.suggestheight) {
        alert('建议图片格式为' + parent.suggestwidth + '*' + parent.suggestheight);
    }

    jcrop_api.setImage(getFullPath(obj));
    jcrop_api.animateTo([0,0,parent.minwidth, parent.minheight]);

    $("#previewid").attr("src", getFullPath(obj));
  
    imagesize = jcrop_api.getBounds();
    setTimeout(function() {
    	var imgWidth = 440 - (440 - document.getElementsByClassName('jcrop-tracker')[1].style.width.split('px')[0])/2;
    	var imgHeight= (440 - document.getElementsByClassName('jcrop-tracker')[1].style.height.split('px')[0])/2;
    	console.log('imgHeight='+imgHeight);
    		$('.jcrop-holder').css({'top':imgHeight, 'display': 'block'});
    		var top=-imgHeight+'px';
    		console.log('top='+top);
    	$('#preview-pane').css({'left': imgWidth + 18, 'display': 'block','top':top,'color':'red'});
    	
    	
    }, 500);
}